/*
 * Command.cpp
 *
 *  Created on: Jan 29, 2012
 *      Author: xum
 */
#include "Command.h"

#include "HardwareSerial.h"
#include <WString.h>

extern HardwareSerial Serial;
char * commandBuf = new char[BUFFER_LEN];

Command::Command() {

}
Command::Command(String _name, String args[]) {
	this->name = String(_name);
	for (unsigned int i = 0; i < sizeof(args); ++i) {
		this->arguments[i] = String(args[i]);
	}
}

//
Command::~Command() {
//	delete &name;
//	for (unsigned int i = 0; i < sizeof(arguments); ++i) {
//		delete &arguments[i];
//	}
//	delete[] arguments;
}

String Command::getArgument(int i) {
	return this->arguments[i];
}

int Command::getInteger(int i) {
	char temp[MAX_ARG_LEN];
	this->arguments[i].toCharArray(temp, MAX_ARG_LEN+1);
	int x = atoi(temp);
	if ( this->arguments[i] == NULL) {
		Serial.println("IS NULL");
		x = -1;
	}
	return x;

}

String Command::getName() {
	return this->name;
}

Command Command::parseCommand(String text) {
	Command result = Command();

	text.toCharArray(commandBuf, BUFFER_LEN);
	int currentSep = text.indexOf(SEPARATOR);
	result.name = String(text.substring(0, currentSep));
	int lastSep = currentSep;
	int i = 0;
	while ((currentSep = text.indexOf(SEPARATOR, lastSep + 1)) != -1) {
		result.arguments[i] = String(text.substring(lastSep + 1, currentSep));
		lastSep = currentSep;
		i++;
	}
;

	if (lastSep!=-1 && i < MAX_ARGS) {

		result.arguments[i] = String(text.substring(lastSep+1));
	}
	return result;
}

